package www.zengzhuo.cn.mac.launch;

import com.dd.plist.NSDictionary;
import com.dd.plist.NSNumber;
import com.dd.plist.NSObject;
import com.dd.plist.PropertyListParser;
import www.zengzhuo.cn.mac.enums.LaunchType;

import java.io.File;

public class LaunchPList {

    private final File plist;
    private final LaunchType launchType;
    private NSDictionary dictionary = null;
    private Boolean keepAlive;
    private Boolean runAtLoad;
    private Boolean successfulExit;

    public LaunchPList(File plist, LaunchType launchType) {
        this.plist = plist;
        this.launchType = launchType;
    }

    public File getPlist() {
        return this.plist;
    }

    public LaunchType getLaunchType() {
        return launchType;
    }

    public Boolean getKeepAlive() {
        ensureParse();
        return keepAlive;
    }

    public Boolean getRunAtLoad() {
        ensureParse();
        return runAtLoad;
    }

    public Boolean getSuccessfulExit() {
        ensureParse();
        return successfulExit;
    }

    public String getXMLPropertyList() {
        ensureParse();
        return dictionary.toXMLPropertyList();
    }

    private Boolean getBooleanValue(String key) {
        NSObject value = null;
        if (dictionary.containsKey(key)) {
            value = dictionary.objectForKey(key);
            if (value instanceof NSNumber) {
                NSNumber number = (NSNumber) value;
                return Boolean.valueOf(number.boolValue());
            }
        }
        return null;
    }

    public boolean isAutoRun() {
        ensureParse();
        return keepAlive == Boolean.TRUE || runAtLoad == Boolean.TRUE || successfulExit != null;
    }

    private synchronized void ensureParse() {
        if (dictionary == null) {
            try {
                this.dictionary = (NSDictionary) PropertyListParser.parse(plist);
                this.keepAlive = getBooleanValue("KeepAlive");
                this.runAtLoad = getBooleanValue("RunAtLoad");
                this.successfulExit = getBooleanValue("SuccessfulExit");

            } catch (Exception e) {
                e.printStackTrace();
                dictionary = null;
                keepAlive = null;
                runAtLoad = null;
                successfulExit = null;
            }
        }
    }

    @Override
    public String toString() {
        ensureParse();
        return "LaunchPList [plist=" + plist.getAbsolutePath() + ", launchType=" + launchType + ", keepAlive=" + keepAlive
                + ", runAtLoad=" + runAtLoad + ", successfulExit=" + successfulExit + "]";
    }
}
